﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using masterview.Code.models;

namespace masterview.Code.db
{
    public class DatabaseHelper : DatabaseConnectionHelper
    {
        #region Static Methods

        protected static void GatherServiceParamater(List<CmsDocsServiceExtendedModel> services, SqlDataReader reader)
        {
            if (!reader.HasRows) return;

            //temp variables
            var tempSettingValue = String.Empty;
            var tempSettingName = String.Empty;

            long serviceId = -1; //as a flag

            while (reader.Read())
            {
                var dbServiceId = Convert.ToInt32(reader["INSTALL_ID"]);
                if (serviceId != dbServiceId)
                {
                    serviceId = dbServiceId;
                    //creates new service
                    var service = new CmsDocsServiceExtendedModel();
                    service.ID = serviceId;
                    service.Name = (string)reader["COMPUTER_NAME"];

                    //gets all parameter
                    var parameters = new Dictionary<string, string>();
                    if (!String.IsNullOrEmpty(tempSettingValue) && !String.IsNullOrEmpty(tempSettingName))
                    {
                        parameters.Add(tempSettingName, tempSettingValue);
                        tempSettingName = String.Empty;
                        tempSettingValue = String.Empty;
                    }
                    do
                    {
                        parameters.Add((string)reader["SETTING_NAME"], (string)reader["SETTING_VALUE"]);
                        if ((reader["SETTING_NAME"]).Equals(CmsDocsServiceSimpleModel.CmsDocsServiceSetting.CmsConnectionString))
                        {
                            service.Database = GetDatabaseNameFromConnectionString((string)reader["SETTING_VALUE"]);
                        }
                    } while (reader.Read() && serviceId == Convert.ToInt32(reader["INSTALL_ID"]));
                    
                    
                    service.ServiceParameters = parameters; //sets parameters to service
                    services.Add(service);                  //adds service to list

                    //hack! или костыль, проще говоря.
                    try
                    {
                        tempSettingName = (string)reader["SETTING_NAME"];
                        tempSettingValue = (string)reader["SETTING_VALUE"];
                    }
                    catch (Exception ex)
                    {
                        //skip
                    }
                }
            }
        }

        private static string GetDatabaseNameFromConnectionString(string connectionString)
        {
            var sb = new SqlConnectionStringBuilder(connectionString);
            return sb.InitialCatalog;
        }

        protected static List<string> GetDistinctIdsFromInstancesList(List<CmsDocsServiceExtendedInstanceModel> instances)
        {
            return instances == null ? null : instances.Select(instance => instance.InstallId.ToString()).ToList();
        }

        protected static void SetInstancesForServices(List<CmsDocsServiceExtendedModel> services, List<CmsDocsServiceExtendedInstanceModel> instances)
        {
            try
            {
                if (services == null || services.Count == 0 ||
                    instances == null || instances.Count == 0) return;

                foreach (var service in services)
                {
                    foreach (var instance in instances)
                    {
                        if (service.ID == instance.InstallId) service.Instances.Add(instance);
                    }
                }
            }
            catch (Exception e)
            {
                throw new ApplicationException(e.StackTrace);
            }
        }

        protected static void GatherAdditionalInstanceInformation(CmsDocsServiceExtendedInstanceModel instance, SqlDataReader reader)
        {
            if (!reader.HasRows) return;

            var tempOfficeCode = String.Empty;

            var serviceId = -1;

            while (reader.Read())
            {
                var dbServiceId = Convert.ToInt32(reader["CMS_WEBSERVICE_ID"]);
                if (serviceId != dbServiceId)
                {
                    serviceId = dbServiceId;
                    //creates new service
                    var usedInstance = new CmsDocsServiceUsedInstanceInformationModel();
                    usedInstance.ID = dbServiceId;
                    usedInstance.Name = (string)reader["CMS_WEBSERVICE_LOCATION_NAME"];

                    //gets all parameter
                    var offices = new List<string>();

                    if (!String.IsNullOrEmpty(tempOfficeCode))
                    {
                        offices.Add(tempOfficeCode);
                        tempOfficeCode = String.Empty;
                    }

                    do
                    {
                        offices.Add((string)reader["OFFICE_CODE"]);
                    } while (reader.Read() && serviceId == Convert.ToInt32(reader["CMS_WEBSERVICE_ID"]));

                    usedInstance.Offices = offices; //sets offices codes
                    instance.UsedInstances.Add(usedInstance);

                    try
                    {
                        tempOfficeCode = (string)reader["OFFICE_CODE"];
                    }
                    catch
                    {
                        //skip
                    }
                }

            }
        }

        #endregion
    }    
}